package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.mapper.TempleteRecordMapper;
import com.vast.admin.entity.TempleteRecord;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TempleteRecordService extends ServiceImpl<TempleteRecordMapper, TempleteRecord> {

    /**
     * 将模板记录设置为当前使用
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void setUse(Long id, Long templeteId) {
        UpdateWrapper<TempleteRecord> notUseUpdateWrapper = new UpdateWrapper<>();
        notUseUpdateWrapper.eq(TempleteRecord.COL_TEMPLETE_ID, templeteId)
                .ne("id", id);
        //设置为未使用
        notUseUpdateWrapper.set(TempleteRecord.COL_IS_USE, 0);
        super.update(notUseUpdateWrapper);
        UpdateWrapper<TempleteRecord> useUpdateWrapper = new UpdateWrapper<>();
        useUpdateWrapper.eq("id", id);
        useUpdateWrapper.set(TempleteRecord.COL_IS_USE, 1);
        super.update(useUpdateWrapper);
    }

    /**
     * 根据模板id获取当前使用的模板记录
     * @param templeteId
     * @return
     */
    public TempleteRecord getByTempleteId(Long templeteId) {
        if (templeteId == null) {
            return null;
        }
        QueryWrapper<TempleteRecord> templeteRecordQueryWrapper = new QueryWrapper<>();
        templeteRecordQueryWrapper.eq(TempleteRecord.COL_TEMPLETE_ID, templeteId)
                .eq(TempleteRecord.COL_IS_USE, 1)
                .orderByDesc(TempleteRecord.COL_CREATE_TIME);
        List<TempleteRecord> templeteRecords = super.list(templeteRecordQueryWrapper);
        if (templeteRecords != null && !templeteRecords.isEmpty()) {
            return templeteRecords.get(0);
        }
        return null;
    }
}
